﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
using System.Collections.ObjectModel;
using BlueRadar.API;
using System.Threading;
using Microsoft.Win32;
using System.IO;

namespace BlueRadar.UI
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        #region Private Properites
        private BackgroundWorker bg_search;
        private DeviceControl SelectedDevice;
        private string FilePath;
        private Brush defaultcolor;
        private BlueSupport support;
        private delegate void Execute();
        #endregion

        #region Constructor
        public MainWindow()
        {
            InitializeComponent();

            if (IsBluetoothSupported())
            {
                BrushConverter con = new BrushConverter();
                defaultcolor = con.ConvertFromString("#3FC7C7C7") as Brush;


                OnClick_BeginStoryboard.Storyboard.Completed += new EventHandler(Storyboard_Completed);

                bg_search = new BackgroundWorker();
                bg_search.DoWork += new DoWorkEventHandler(bg_search_DoWork);
                bg_search.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bg_search_RunWorkerCompleted);
            }
            else
                this.Close();
        }

        #endregion

        #region Support

        bool IsBluetoothSupported()
        {
            support = new BlueSupport();

            if (support.IsBluetoothSupported)
            {
                // Todo - Add button to main ui to enable users to change computer bluetooth mode.
                //if (!support.IsDiscoverable)
                //{
                //    if (MessageBox.Show("Make BluetoothRadio Discoverable?", "Bluetooth Radar", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                //    {
                //        support.MakeDiscoverable();
                //    }
                //}
                return true;
            }
            else
            {
                MessageBox.Show("No support Bluetooth radio/stack found.\n\nBluetooth Radar requires active Bluetooth device", "Bluetooth Radar", MessageBoxButton.OK, MessageBoxImage.Information);
                return false;
            }
        }

        #endregion

        #region Radar UI + Actions

        void Storyboard_Completed(object sender, EventArgs e)
        {
            OnClick_BeginStoryboard.Storyboard.Begin();
        }

        private PositionHelper pos_helper;
        void GetPos(Device device)
        {
            pos_helper.Random();

            device.X = pos_helper.X;
            device.Y = pos_helper.Y;
            SetDeviceOnRadar(device);
        }

        private void SetDeviceOnRadar(Device device)
        {
            DeviceControl d = new DeviceControl(device);
            this.RadarGrid.Children.Add(d);

            d.MouseEnter += new MouseEventHandler(d_MouseEnter);
            d.MouseLeave += new MouseEventHandler(d_MouseLeave);
            d.MouseDown += new MouseButtonEventHandler(d_MouseDown);
            d.Cursor = Cursors.Hand;

            Canvas.SetLeft(d, device.Y);
            Canvas.SetTop(d, device.X);
        }

        void d_MouseDown(object sender, MouseButtonEventArgs e)
        {
            GridDetails.Visibility = System.Windows.Visibility.Visible;
            DeviceControl control = e.Source as DeviceControl;
            if (control != null)
            {
                SelectedDevice = control;

                if (SelectedDevice.Device.ObexEnabled)
                {
                    btn_browse.IsEnabled = true;
                    btn_send.IsEnabled = true;
                }
                else
                {
                    btn_browse.IsEnabled = false;
                    btn_send.IsEnabled = false;
                }

                DeviceDetailsList.Items.Clear();
                DeviceDetailsList.Items.Add(control.Device);
            }
        }

        void d_MouseLeave(object sender, MouseEventArgs e)
        {
            DeviceControl d = e.Source as DeviceControl;
            if (d != SelectedDevice)
                d.SetValue(Canvas.ZIndexProperty, 1);
        }

        void d_MouseEnter(object sender, MouseEventArgs e)
        {
            DeviceControl d = e.Source as DeviceControl;
            d.SetValue(Canvas.ZIndexProperty, 100);
        }
        #endregion

        #region BackgroundWorker
        void bg_search_DoWork(object sender, DoWorkEventArgs e)
        {
            ObservableCollection<Device> DevicesFound = Common.SearchDevices(Properties.Settings.Default.maxDevices,
                Properties.Settings.Default.authenticated,Properties.Settings.Default.remembered,
                Properties.Settings.Default.unknown,Properties.Settings.Default.discoveredonly);
            e.Result = DevicesFound;
        }

        void bg_search_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            ObservableCollection<Device> DevicesFound = e.Result as ObservableCollection<Device>;
            foreach (Device device in DevicesFound)
                GetPos(device);
            ScanningDone();
        }
        #endregion

        #region UI + Animation
        private void Drag(object sender, MouseButtonEventArgs e)
        {
            if(e.ChangedButton == MouseButton.Left)
                this.DragMove();
        }

        void ScanningDone()
        {
            search_btn.IsEnabled = true;
            this.path.Visibility = Visibility.Hidden;
            OnClick_BeginStoryboard.Storyboard.Stop();
        }

        void StartScanning()
        {
            search_btn.IsEnabled = false;
            CleanRadarItem();
            GridDetails.Visibility = System.Windows.Visibility.Hidden;
            this.path.Visibility = Visibility.Visible;
        }

        void CleanRadarItem()
        {
            List<UIElement> OldDevices = new List<UIElement>();
            foreach (UIElement device in this.RadarGrid.Children)
            {
                if (device.GetType().Name == "DeviceControl")
                    OldDevices.Add(device);
            }
            foreach (UIElement device in OldDevices)
                this.RadarGrid.Children.Remove(device);
        }

        #endregion

        #region UI Actions
        private void close_btn_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }

        private void search_btn_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (!bg_search.IsBusy)
            {
                StartScanning();
                pos_helper = new PositionHelper(this.RadarGrid);
                bg_search.RunWorkerAsync();
            }
        }

        void StartSending()
        {
            BlueSender bsender = new BlueSender(SelectedDevice.Device, FilePath);
            bsender.SendFile();

            Execute ex = delegate()
            { DeviceDetailsList.Items.Refresh();
            }; this.Dispatcher.Invoke(ex, null);
        }

        private void btn_send_Click(object sender, RoutedEventArgs e)
        {
            if (FilePath != null && File.Exists(FilePath))
            {
                SelectedDevice.Device.LastSendStatus = "Sending...";
                DeviceDetailsList.Items.Refresh();
                Thread t = new Thread(new ThreadStart(StartSending));
                t.Start();
            }
            else
            {
                if (MessageBox.Show("Please select file before trying sending it...\nWould you like to select file?", "Missing File To Send", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                {
                    btn_browse_Click(sender, e);
                }
            }
        }

        private void btn_browse_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();
            fd.Title = "Select File To Send";
            fd.ShowDialog();
            if (!string.IsNullOrEmpty(fd.FileName))
            {
                FilePath = fd.FileName;
            }
        }

        private void btn_info_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (e.ChangedButton == MouseButton.Left)
            {
                DeviceInformation info_window = new DeviceInformation();
                SetWindowPosition(info_window);
                info_window.ShowDialog();
            }
        }

        private void SetWindowPosition(Window win)
        {
            win.Left = this.Left + 100;
            win.Top = this.Top + 108;
        }

        #endregion

        private void btn_settings_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Settings settings = new Settings();
            SetWindowPosition(settings);
            settings.ShowDialog();
        }

    }
}
